import time
from loguru import logger
from DrissionPage import Chromium
from DrissionPage.errors import ElementLostError, NoRectError, ElementNotFoundError
from read_search_file import get_complete_sheet1, get_complete_sheet_platform, get_complete_sheet_indus_people, get_complete_sheet_indus_inters, get_complete_sheet_keyword, get_complete_sheet_crowd_pack, mock_click_js
from DrissionPage.common import Keys
from create_creative import create_creative_func
import pandas as pd


'''创建单元'''



def log_message(log_callback, message, color=None):
    if callable(log_callback):
        log_callback(message, color) if color else log_callback(message)
# 填充平台精选
def select_platform_vip_choose(u_view_tab, r_excel, df_platform):
    main_crowed_pack = r_excel['人群定向包']
    for p_row in df_platform.itertuples():
        if main_crowed_pack == p_row.人群定向包:
            print(f"当前循环到的小类:{p_row.小类}")
            one_option_arr = p_row.一级选项.split('\n')
            if '场景人群' == p_row.小类:
                for option in one_option_arr:
                    u_view_tab.ele(f'tag:span@@ class$--color-text-title --size-text-paragraph d-text-nowrap d-text-ellipsis@@style=max-width: 126px;@@text()={option.strip()}').scroll.to_see()
                    u_view_tab.ele(f'tag:span@@ class$--color-text-title --size-text-paragraph d-text-nowrap d-text-ellipsis@@style=max-width: 126px;@@text()={option.strip()}').parent(2).prev().prev().click(by_js=True)
            if '节促人群' == p_row.小类:
                for option in one_option_arr:
                    u_view_tab.ele(f'tag:span@@text()={option.strip()}').scroll.to_see()
                    u_view_tab.ele(f'tag:span@@text()={option.strip()}').parent(3).run_js('this.click();')

# 填充行业人群
def select_indus_people(u_view_tab, r_excel, df_platform):
    main_crowed_pack = r_excel['人群定向包']
    for indus_row in df_platform.itertuples():
        if main_crowed_pack == indus_row.人群定向包:
            one_section = indus_row.一级选项.strip()
            if '策略人群' == indus_row.小类:
                u_view_tab.ele('css:div:nth-child(6) .d-segment-item:nth-child(1)').click(by_js=True)  # 点击策略人群
                if not one_section == '全选':
                    u_view_tab.ele(f'tag:span@@text()=一级行业').parent(1).next().child().ele(f'tag:span@@class$--color-text-paragraph --size-text-paragraph text label@@text()={one_section}').prev(1, "tag:div").click(by_js=True)  ## 选中一级选项
                    # u_view_tab.ele(f'x:/html/body/div[2]/div/div/div/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[2]/div[2]/div[1]/div/div/div/div[5]/div[2]/div[1]/div[2]/div[1]//span[text()="{one_section}"]').prev(1, "tag:div").click(by_js=True)  ## 选中一级选项
                    if pd.notna(indus_row.二级选项):
                        # 取消策略人群人群包全选
                        u_view_tab.ele('css:.form-section:nth-child(4) > .promotion-group > div:nth-of-type(2) > div.form.custom-target > div > div > div > div:nth-child(6) > div:nth-of-type(2)> div:nth-of-type(1) .delight-material-cascader-panel > div.delight-material-cascader-menu:nth-child(3) .delight-material-cascader-node-all span.d-checkbox-indicator').click(by_js=True)

                        strategy_second_option_arr = indus_row.二级选项.split('\n')
                        for s in strategy_second_option_arr: ## 遍历策略人群二级选项
                            u_view_tab.ele(f'tag:span@@text()={s.strip()}').prev(1, 'tag:div').click(by_js=True)
                else:
                    u_view_tab.ele('css:.form-section:nth-child(4) > .promotion-group > div:nth-of-type(2) > div.form.custom-target > div > div > div > div:nth-child(6) > div:nth-of-type(2)> div:nth-of-type(1) .delight-material-cascader-panel > div.delight-material-cascader-menu:nth-child(1) .delight-material-cascader-node-all span.d-checkbox-indicator').click(by_js=True)
            if '垂类人群' == indus_row.小类:
                u_view_tab.ele('css:div:nth-child(6) .d-segment-item:nth-child(2)').click(by_js=True) # 点击垂类人类
                if not one_section == '全选':
                    u_view_tab.ele(f'x:/html/body/div[2]/div/div/div/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[2]/div[2]/div[1]/div/div/div/div[5]/div[2]/div[2]/div[2]/div[1]//span[text()="{one_section}"]').prev(1, 'tag:div').click(by_js=True)  ## 选中一级选项
                    if pd.notna(indus_row.二级选项):
                        # 取消垂类人群人群包全选
                        u_view_tab.ele(
                            'css:.form-section:nth-child(4) > .promotion-group > div:nth-of-type(2) > div.form.custom-target > div > div > div > div:nth-child(6) > div:nth-of-type(2)> div:nth-of-type(2)   .delight-material-cascader-panel > div.delight-material-cascader-menu:nth-child(3) .delight-material-cascader-node-all span.d-checkbox-indicator').click(by_js=True)
                        strategy_second_option_arr = indus_row.二级选项.split('\n')
                        for s in strategy_second_option_arr:  ## 遍历垂类人群二级选项
                            u_view_tab.ele(f'tag:span@@text()={s.strip()}').prev(1, 'tag:div').click(by_js=True)
                else:
                    u_view_tab.ele('css:.form-section:nth-child(4) > .promotion-group > div:nth-of-type(2) > div.form.custom-target > div > div > div > div:nth-child(6) > div:nth-of-type(2)> div:nth-of-type(2) .delight-material-cascader-panel > div.delight-material-cascader-menu:nth-child(1) .delight-material-cascader-node-all span.d-checkbox-indicator').click(by_js=True)


# 填充行业兴趣
def select_indus_inters_people(u_view_tab, r_excel, df_indus_people):
    main_crowed_pack = r_excel['人群定向包']

    for indus_row in df_indus_people.itertuples():
        if main_crowed_pack == indus_row.人群定向包:
            one_section = indus_row.一级选项.strip()
            if '行业阅读兴趣' == indus_row.小类:
                if not one_section == '全选':
                    u_view_tab.ele(f'x:/html/body/div[1]/div/div/div/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[2]/div[2]/div[1]/div/div/div/div[6]/div[2]/div[1]/div[2]/div[1]/div/div/ul//span[text()="{one_section}"]').prev(1, 'tag:div').click()  ## 选中阅读兴趣一级选项
                else:
                    u_view_tab.ele('css:.form-section:nth-child(4) > .promotion-group > div:nth-of-type(2) > div.form.custom-target > div > div > div > div:nth-child(7) > div:nth-of-type(2) > div:nth-of-type(1) .delight-material-cascader-panel > div.delight-material-cascader-menu:nth-child(1) .delight-material-cascader-node-all span.d-checkbox-indicator').run_js('this.click();')
            if '行业购物兴趣' == indus_row.小类:
                u_view_tab.ele('css:div:nth-child(7) .d-segment-item:nth-child(2)').wait(0.5).run_js('this.click();') # 点击行业购物兴趣
                if not one_section == '全选':
                    u_view_tab.ele(f'x:/html/body/div[1]/div/div/div/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[2]/div[2]/div[1]/div/div/div/div[6]/div[2]/div[2]/div[2]/div[1]//span[text()="{one_section}"]').prev(1, 'tag:div').run_js('this.click();')  ## 选中购物兴趣一级选项
                    if pd.notna(indus_row.二级选项):
                        # 取消行业购物兴趣二级兴趣全选
                        u_view_tab.ele('css:.form-section:nth-child(4) > .promotion-group > div:nth-of-type(2) > div.form.custom-target > div > div > div > div:nth-child(7) > div:nth-of-type(2) > div:nth-of-type(2)> div:nth-of-type(2)  > div:nth-of-type(3) li.delight-material-cascader-node-all > div').run_js('this.click();')
                        indus_inters_second_option_arr = indus_row.二级选项.split('\n')  ## 行业购物兴趣二级兴趣
                        for s in indus_inters_second_option_arr:  ## 遍历行业购物兴趣二级选项
                            u_view_tab.ele(f'tag:span@@text()={s.strip()}').prev(1, 'tag:div').run_js('this.click();')
                else:
                    u_view_tab.ele('css:.form-section:nth-child(4) > .promotion-group > div:nth-of-type(2) > div.form.custom-target > div > div > div > div:nth-child(7) > div:nth-of-type(2)> div:nth-of-type(2) .delight-material-cascader-panel > div.delight-material-cascader-menu:nth-child(1) .delight-material-cascader-node-all span.d-checkbox-indicator').run_js('this.click();')
def select_keyword_people(u_view_tab, r_excel, df_keyword):
    main_crowed_pack = r_excel['人群定向包']
    u_view_tab.ele('tag:span@@text()=智能扩量').scroll.to_center()
    for word_row in df_keyword.itertuples():
        if main_crowed_pack == word_row.人群定向包:
            small_type = word_row.小类
            keyword_option_arr = word_row.关键词.split('\n')  ## 关键词列表
            if '关键词兴趣' == small_type:
                u_view_tab.ele('tag:div@@class=flexible align-center@@text()=关键词兴趣').parent(3).click(by_js=True)  # 点击关键词兴趣
                for k in keyword_option_arr:
                    try:
                        u_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder=请输入关键词').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', k.strip()) # 输入关键词兴趣查询框
                        u_view_tab.ele('css:div.search-icon:nth-child(2) > span').run_js('this.click();') # 点击关键词兴趣搜索按钮
                        if keyword_move_ele := u_view_tab.ele(f'tag:span@@class$--color-text-title --size-text-paragraph d-text-nowrap d-text-ellipsis@@style=text-underline-offset: auto; max-width: 120px;@@text()={k.strip()}', timeout=1):
                            if add_ele := keyword_move_ele.parent(2).next().next().child().child().child('@text()= 添加 ', timeout=1.5):
                                add_ele.run_js('this.click();')  # 点击选择
                                u_view_tab.wait(0.3)
                    except (ElementLostError, NoRectError, AttributeError) as e:
                        print(e)
                        continue

            if '行为' in small_type:
                # u_view_tab.ele('css:.d-button:nth-child(2) .flexible').click()  # 点击关键词行为
                u_view_tab.ele('tag:div@@class=flexible align-center@@text()=关键词行为').parent(3).click(by_js=True)  # 点击关键词行为
                u_view_tab.ele('css:.period > .d-select-wrapper:nth-child(1) .d-select-content').click(by_js=True)  # 点击时间下拉框
                if ':' in small_type:  # 如果存在条件搜索
                    time_and_range = small_type.split(':')[1]
                    time_sel = time_and_range.split('-')[0]
                    content_range = time_and_range.split('-')[1]
                    u_view_tab.ele(f'tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis@@text()={time_sel.strip()}').run_js('this.click();')  # 点击时间下拉框
                    u_view_tab.ele('css:.d-select-content:nth-child(1) > .d-select-input-filter > .d-text:nth-child(1)').click(by_js=True)  # 点击关键词内容框
                    u_view_tab.ele('css:body > div.d-dropdown:nth-last-of-type(1) .d-options-wrapper > div > div:nth-child(3) > div >span').run_js('this.click();')  ## 清空搜索选项
                    for r in content_range.split(';'):
                        if r == '搜索':
                            u_view_tab.ele('css:body > div.d-dropdown:nth-last-of-type(1) .d-options-wrapper > div > div:nth-child(3) > div >span').run_js('this.click();')  # 选中搜索
                        if r == '互动':
                            u_view_tab.ele('css:body > div.d-dropdown:nth-last-of-type(1) .d-options-wrapper > div > div:nth-child(6) > div >span').run_js('this.click();')  # 选中互动
                        if r == '阅读':
                            u_view_tab.ele('css:body > div.d-dropdown:nth-last-of-type(1) .d-options-wrapper > div > div:nth-child(9) > div >span').run_js('this.click();')  # 选中阅读

                # 否则直接输入关键词
                u_view_tab.ele('css:.keyword-search-input .d-text').click(by_js=True)  # 点击关键词
                u_view_tab.ele('tag:span@@text()=智能扩量').scroll.to_center()

                for k in keyword_option_arr:
                    try:
                        u_view_tab.ele('css:.keyword-search-input .d-text').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', k.strip()) # 输入关键词行为查询框
                        u_view_tab.ele('css:div.search-icon:nth-child(2) > span').run_js('this.click();') # 点击关键词行为搜索按钮
                        u_view_tab.wait(0.3)

                        if keyword_move_ele := u_view_tab.ele(f'tag:span@@class=d-text --color-static --color-text-title --size-text-paragraph d-text-nowrap d-text-ellipsis@@style=text-underline-offset: auto; max-width: 120px;@@text()={k.strip()}', timeout=1):
                            keyword_move_ele.scroll.to_center()
                            add_ele = keyword_move_ele.parent(2).next().next().child().child().child('@text()= 添加 ', timeout=1.5)
                            if add_ele:
                                add_ele.run_js('this.click();') # 点击选择
                    except (ElementLostError, NoRectError, AttributeError) as e:  # AttributeError
                        print(e)
                        continue
def select_df_crowd_pack(u_view_tab, r_excel, df_crowd_pack):
    main_crowed_pack = r_excel['人群定向包']

    for crowd_row in df_crowd_pack.itertuples():
        if main_crowed_pack == crowd_row.人群定向包:
            pack_names = crowd_row.包名
            pack_name_arr = pack_names.split('\n')  ## 关键词列表
            pack_name_arr = list(set(pack_name_arr))  ## 去重
            u_view_tab.ele('css:.d-select-input-filter > .d-text:nth-child(1)').run_js('this.click();')  # 点击人群包查询框
            for p in pack_name_arr:
                u_view_tab.ele('css:.d-select-input-filter > .d-text:nth-child(1)').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', p.strip())  # 输入包名
                u_view_tab.wait(0.3)
                if pack_input := u_view_tab.ele(f'tag:span@@class$--color-text-title --size-text-paragraph@@text()^{p.strip()}', timeout=2):
                    logger.info(f"搜出来的包名:{pack_input.parent(2).child()}")
                    class_str_crowed_pack = pack_input.parent(2).child().attr('class')
                    if 'unchecked' in class_str_crowed_pack:
                        pack_input.run_js('this.click();')  # 选择人群包
                    else:
                        continue
                else:
                    continue

'''选择高级定向'''
def select_senior_target(u_view_tab, r_excel, file_path, log_callback):
    plan_crowd_pack = r_excel['人群定向包']
    plan_name = r_excel['计划名']

    combine_pack_arr = []

    # 选中平台精选
    df_platform = get_complete_sheet_platform(file_path)
    if not df_platform.empty:
        platform_crowd_pack_arr = df_platform['人群定向包'].tolist()
        combine_pack_arr.extend(platform_crowd_pack_arr)

        if plan_crowd_pack in platform_crowd_pack_arr:
            platform_choose_ele = u_view_tab.ele('tag:span@@text()=平台精选', timeout=5)
            if not platform_choose_ele:
                u_view_tab.ele('tag:input@@type=radio@@value=3').parent(1).click(by_js=True)  # 点击高级定向
            platform_choose_ele.run_js('this.click();') # 点击平台精选
            platform_choose_ele.scroll.to_center() # 滚到中间
            select_platform_vip_choose(u_view_tab, r_excel, df_platform)
        # else:
        #     log_message(log_callback, f"当前计划人群定向包列:{plan_crowd_pack}在【平台精选】选项卡中不存在, 检查主表计划名:{plan_name} - 人群定向包列", "red")
        #     return

    # 选中行业人群
    df_indus_people = get_complete_sheet_indus_people(file_path)
    if not df_indus_people.empty:
        df_indus_people_arr = df_indus_people['人群定向包'].tolist()
        combine_pack_arr.extend(df_indus_people_arr)

        if plan_crowd_pack in df_indus_people_arr:
            indus_crowd_ele = u_view_tab.ele('tag:span@@class$--color-text-paragraph --size-text-paragraph d-clickable@@text()=行业人群', timeout=5)
            if not indus_crowd_ele:
                u_view_tab.ele('tag:input@@type=radio@@value=3').parent(1).click(by_js=True)  # 点击高级定向
            indus_crowd_ele.click(by_js=True)  # 点击行业人群
            select_indus_people(u_view_tab, r_excel, df_indus_people)
        # else:
        #     log_message(log_callback, f"当前计划人群定向包列:{plan_crowd_pack}在【行业人群】选项卡中不存在, 检查主表计划名:{plan_name} - 人群定向包列", "red")
        #     return

    # 选中行业兴趣
    df_indus_inters_people = get_complete_sheet_indus_inters(file_path)
    if not df_indus_inters_people.empty:
        df_indus_inters_arr = df_indus_inters_people['人群定向包'].tolist()
        combine_pack_arr.extend(df_indus_inters_arr)

        if plan_crowd_pack in df_indus_inters_arr:
            indus_interest_ele = u_view_tab.ele('tag:span@@class$--color-text-paragraph --size-text-paragraph d-clickable@@text()=行业兴趣', timeout=5)
            if not indus_interest_ele:
                u_view_tab.ele('tag:input@@type=radio@@value=3').parent(1).click(by_js=True)  # 点击高级定向
            indus_interest_ele.click(by_js=True)  # 点击行业兴趣
            select_indus_inters_people(u_view_tab, r_excel, df_indus_inters_people)
        # else:
        #     log_message(log_callback, f"当前计划人群定向包列:{plan_crowd_pack}在【行业兴趣】选项卡中不存在, 检查主表计划名:{plan_name} - 人群定向包列", "red")
        #     return

    # 选中关键词
    df_keyword = get_complete_sheet_keyword(file_path)
    if not df_keyword.empty:
        df_keyword_arr = df_keyword['人群定向包'].tolist()
        combine_pack_arr.extend(df_keyword_arr)

        if plan_crowd_pack in df_keyword_arr:
            keyword_ele = u_view_tab.ele('tag:span@@class$--color-text-paragraph --size-text-paragraph d-clickable@@text()=关键词', timeout=5)
            if not keyword_ele:
                u_view_tab.ele('tag:input@@type=radio@@value=3').parent(1).click(by_js=True)  # 点击高级定向
            keyword_ele.click(by_js=True)  # 点击关键词
            select_keyword_people(u_view_tab, r_excel, df_keyword)
        # else:
        #     log_message(log_callback, f"当前计划人群定向包列:{plan_crowd_pack}在【关键词】选项卡中不存在, 检查主表计划名:{plan_name} - 人群定向包列", "red")
        #     return

    # 选中人群包
    df_crowd_pack = get_complete_sheet_crowd_pack(file_path)
    if not df_crowd_pack.empty:
        df_crowd_pack_arr = df_crowd_pack['人群定向包'].tolist()
        combine_pack_arr.extend(df_crowd_pack_arr)

        if plan_crowd_pack in df_crowd_pack_arr:
            crowd_pack_ele = u_view_tab.ele('tag:span@@class$--color-text-paragraph --size-text-paragraph d-clickable@@text()=人群包', timeout=5)
            if not crowd_pack_ele:
                u_view_tab.ele('tag:input@@type=radio@@value=3').parent(1).click(by_js=True)  # 点击高级定向
            crowd_pack_ele.click(by_js=True)  # 点击人群包
            select_df_crowd_pack(u_view_tab, r_excel, df_crowd_pack)
        # else:
        #     log_message(log_callback, f"当前计划人群定向包列:{plan_crowd_pack}在【人群包】选项卡中不存在, 检查主表计划名:{plan_name} - 人群定向包列", "red")
        #     return

    if plan_crowd_pack not in combine_pack_arr:
        logger.info(f"所有子选项卡中的人群定向包列选项:{combine_pack_arr}")
        log_message(log_callback, f"当前计划人群定向包列:【{plan_crowd_pack}】在子选项卡中不存在, 检查主表计划名:【{plan_name}】 - 人群定向包列填写是否正确", "red")
        return
'''选择更多定向'''
def select_more_target(u_view_tab, r_excel):
    gender = r_excel['性别']
    area = r_excel['地域']
    age = r_excel['年龄']
    platform = r_excel['平台']
    tel_price = r_excel['手机价格']

    if more_target_ele := u_view_tab.ele('css:div:nth-child(13) > .d-link', timeout=1):
        more_target_ele.click(by_js=True)

    if gender != '不限' and gender != '全选':
        # gender_class_str = u_view_tab.ele('css:.input div.form-container > .form-content > div.input:nth-of-type(1) > div:nth-child(1) > div > span:nth-of-type(2)',timeout=2).prev().prev().attr('class')
        u_view_tab.ele('tag:span@@text()=性别', timeout=2).scroll.to_center()  # 滚到性别位置
        gender_class_str = u_view_tab.ele('tag:span@@text()=性别', timeout=2).parent(1).next().child().child().child().attr('class')
        if 'unchecked' not in gender_class_str:
            u_view_tab.ele('tag:span@@text()=性别', timeout=2).parent(1).next().child().child().click(by_js=True) ## 取消性别不限
            u_view_tab.ele(f'tag:span@@text()={gender.strip()}').parent(1).click(by_js=True)  ## 点击男或女

    if '中国' in area:
        u_view_tab.ele('tag:span@@text()=自定义').scroll.to_center()
        top_comment_ele_str = u_view_tab.ele('tag:span@@text()=自定义').prev().prev().attr('class')
        if 'unchecked' in top_comment_ele_str:
            u_view_tab.ele('tag:span@@text()=自定义').parent(1).click(by_js=True)  ## 点击自定义
            u_view_tab.ele(f'tag:span@@text()=中国').parent(1).click(by_js=True)  ## 点击中国
        if any(sep in area for sep in [':not', '：not']):
            cities = area.split(':not')[1].strip()
            excludes_cities = cities.split('-')
            for city in excludes_cities:
                city = city.strip()
                if u_view_tab.ele(f'tag:span@@text()={city}'):
                    u_view_tab.ele(f'tag:span@@text()={city}').scroll.to_center()
                    u_view_tab.ele(f'tag:span@@text()={city}').click(by_js=True)

        u_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=下一步').scroll.to_center()  # 滚到更多定向

    if  '不限' != age and age != '全选':
        u_view_tab.ele('css:.input div.form-container > .form-content > div.input:nth-of-type(5) > div:nth-child(1) > div > span:nth-of-type(2)').scroll.to_center()
        u_view_tab.ele('css:.input div.form-container > .form-content > div.input:nth-of-type(5) > div:nth-child(1) > div > span:nth-of-type(2)').click(by_js=True) ## 取消年龄不限
        age_arr = age.split('\n')
        for a in age_arr:
            u_view_tab.ele(f'tag:span@@text()={a.strip()}').parent(1).click(by_js=True)  ## 选中各年龄段

    if '不限' != platform and '全选' != platform:
        u_view_tab.ele('css:.input div.form-container > .form-content > div.input:nth-of-type(6) > div:nth-child(1) > div > span:nth-of-type(2)').click(by_js=True) ## 取消平台不限
        u_view_tab.ele(f'tag:span@@text()={platform.strip()}').parent(1).click(by_js=True)  ## 点击安卓或者ios

    if tel_price != '不限' and tel_price != '全选':
        tel_price_ele = u_view_tab.ele('css:.input div.form-container > .form-content > div.input:nth-of-type(8) > div:nth-child(1) > div > span:nth-of-type(2)')
        tel_price_ele.scroll.to_center()  # 滚到手机价格位置
        tel_price_ele.click(by_js=True) ## 取消手机价格不限
        tel_price_arr = tel_price.split('\n')
        for tel in tel_price_arr:
            if u_view_tab.ele(f'tag:span@@text()={tel.strip()}', timeout=1):
                u_view_tab.ele(f'tag:span@@text()={tel.strip()}').parent(1).click(by_js=True)  ## 选中各手机段
            else:
                if u_view_tab.ele(f'tag:span@@ class$--color-text-title --size-text-paragraph d-text-nowrap d-text-ellipsis d-checkbox-label@@text():{tel.strip()}', timeout=1):
                    u_view_tab.ele(f'tag:span@@ class$--color-text-title --size-text-paragraph d-text-nowrap d-text-ellipsis d-checkbox-label@@text():{tel.strip()}').parent(1).click(by_js=True)  ## 选中各手机段
                else:
                    continue

'''创建单元主流程'''
def create_unit(u_view_tab, r_excel, browser, file_path, plan_next_button_ele=None, df_sheet=None, log_callback=None):
    u_view_tab.wait.load_start()
    u_view_tab.wait.eles_loaded('tag:input@@class=d-text@@placeholder=请输入你的单元名称')

    unit_name = r_excel['单元名称']
    note_id = r_excel['笔记ID']
    relative_pack = r_excel['关联定向包']

    try:
        input_unit_name_ele = u_view_tab.ele('tag:input@@class=d-text@@placeholder=请输入你的单元名称', timeout=5)
        input_unit_name_ele.input(unit_name, clear=True)
    except ElementNotFoundError:
        logger.info(f"单元名称没找到")
        if plan_next_button_ele and u_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder=请输入你的计划名称@@maxlength=50', timeout=2):
            logger.info(f"单元名称没找到, 页面还停留在创建计划页面, 重新点击下一步")
            plan_next_button_ele.run_js('this.click();')
            u_view_tab.wait.load_start()
            input_unit_name_ele = u_view_tab.ele('tag:input@@class=d-text@@placeholder=请输入你的单元名称', timeout=2)
            input_unit_name_ele.input(unit_name, clear=True)

    # 推广方式
    u_view_tab.ele('tag:div@@class=option-item-text@@text()= 自定义选择 ').run_js('this.click();')
    time.sleep(1)

    # 批量添加笔记
    if u_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 批量添加 ', timeout=2):
        batch_add_note_ids(note_id, u_view_tab)
    else: #单条添加
        note_id_arr = str(note_id).strip().split('\n')
        for i, note in enumerate(note_id_arr):
            select_note_and_choose(note, u_view_tab)
            # 二次检查笔记ID是否正确
            while True:
                u_view_tab.ele('tag:div@@text()=笔记id').wait.displayed()
                if u_view_tab.ele('tag:div@@text()=笔记id', timeout=5):
                    note_id_id = u_view_tab.ele('tag:div@@text()=笔记id').parent(3).next().child(index=i+1).child(index=2).text
                    if note_id_id == note:
                        break
                    log_message(log_callback, f'选中的笔记ID有误, 重新选择笔记ID: {i+1} 次', "red")
                    u_view_tab.ele('tag:div@@text()=笔记id').parent(3).next().child(index=i+1).ele('tag:td@@class=d-table__cell--fixed-right d-table-cell-td').child().run_js('this.click();') # 删掉这条笔记重新选
                    select_note_and_choose(note, u_view_tab)



    # 人群定向包
    if pd.isna(relative_pack):
        if r_excel['人群定向包'] not in ['通投', '智能定向']:
            u_view_tab.wait(1)
            # u_view_tab.ele('tag:span@@text()=高级定向').click(by_js=True) # 点击高级定向
            u_view_tab.ele('tag:input@@type=radio@@value=3').scroll.to_center()
            u_view_tab.ele('tag:input@@type=radio@@value=3').parent(1).click(by_js=True)  # 点击高级定向

            u_view_tab.ele('tag:input@@type=radio@@value=3').parent(1).click(by_js=True)  # 点击高级定向

            select_senior_target(u_view_tab, r_excel, file_path, log_callback)
            select_more_target(u_view_tab, r_excel)
        else:
            u_view_tab.ele(f'tag:span@@text()={r_excel["人群定向包"]}').scroll.to_center()
            u_view_tab.ele(f'tag:span@@text()={r_excel["人群定向包"]}').click(by_js=True) ## 否则点击通投或智能定向
            select_more_target(u_view_tab, r_excel)
    else:
        relative_pack = r_excel['关联定向包'].strip()
        choose_relative_pack(relative_pack, u_view_tab)

        # 看看有没有选到高级定向，如果没有一直选关联定向包
        senior_target_class_str = u_view_tab.ele('tag:input@@type=radio@@value=3').prev().attr('class')
        while True:
            if 'unchecked' not in senior_target_class_str:
                break
            choose_relative_pack(relative_pack, u_view_tab)


    # 排除特定人群
    if u_view_tab.ele('tag:span@@text()=排除特定人群', timeout=2):
        if '排除特定人群' in df_sheet.columns:
            exclude_target_crowed = r_excel['排除特定人群']
            if pd.notna(exclude_target_crowed):
                exclude_target_crowed = exclude_target_crowed.strip()
                if exclude_target_crowed != '不排除':
                    u_view_tab.ele('tag:span@@class$--color-text-title --size-text-paragraph@@text()=一方上传人群').run_js(mock_click_js)
                    time.sleep(1)
                    u_view_tab.ele(f'tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis@@style=text-underline-offset: auto;@@text()^{exclude_target_crowed}').run_js('this.click();')

    # 智能扩量
    if '智能扩量' in df_sheet.columns:
        if u_view_tab.ele('tag:span@@text()=智能扩量', timeout=2):
            intelligence_expand = r_excel['智能扩量']
            expand_class_str = u_view_tab.ele('tag:div@@class=intelligentExpansion-switch').child().child().child().child().attr('class')
            if intelligence_expand == '开':
                if 'unchecked' in expand_class_str:
                    u_view_tab.ele('tag:div@@class=intelligentExpansion-switch').child().run_js('this.click();')
            else:
                if 'unchecked' not in expand_class_str:
                    u_view_tab.ele('tag:div@@class=intelligentExpansion-switch').child().run_js('this.click();')

    # select_more_target(u_view_tab, r_excel)

    # time.sleep(1)
    # u_view_tab.ele('css:.footer-action > .--color-bg-primary .d-text').scroll.to_center()
    # 目标成本
    if u_view_tab.ele('css:.flexible:nth-child(1) > .d-input-wrapper .d-text', timeout=2):
        target_cost = r_excel['目标成本']
        if pd.notna(target_cost):
            u_view_tab.ele('css:.flexible:nth-child(1) > .d-input-wrapper .d-text').input(target_cost, clear=True)  # 目标成本

    unit_next_button_ele = u_view_tab.ele('tag:span@@text()=下一步').parent(2)
    unit_next_button_ele.scroll.to_center()
    # unit_next_button_ele.click(by_js=True)  # 点击下一步

    # 处理操作频繁
    handle_operate_too_fast(unit_next_button_ele, u_view_tab, unit_name, log_callback)

    # 弹窗阻塞
    ## d-button d-button-default d-button-with-content --color-static bold --color-bg-primary --color-white
    if alert_remind_range_small_ele := u_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=继续', timeout=2):
        logger.info(f"创建单元界面遇到弹窗阻塞")
        log_message(log_callback, f"单元名称:{unit_name}在创建单元界面遇到弹窗阻塞", "red")
        alert_remind_range_small_ele.parent(2).click(by_js=True)
        unit_next_button_ele.click(by_js=True)  # 点击下一步

    if u_view_tab.ele('tag:span@@class=error@@text()^请选择笔记', timeout=1):
        log_message(log_callback, f"单元名称-{unit_name}-笔记ID-{note_id}不存在", "red")
        return

    if u_view_tab.ele('@text():单元名称已存在', timeout=1):
        log_message(log_callback, f"单元名称:{unit_name} - 已存在", "red")
        return

    if unit_next_button_ele.ele('tag:span@@class=error@@text():高级定向不能为空且不能超过150', timeout=1):
        u_view_tab.ele('tag:input@@type=radio@@value=3').parent(1).click(by_js=True)  # 点击高级定向
        unit_next_button_ele.click(by_js=True)  # 点击下一步

    create_creative_func(u_view_tab, r_excel, browser, file_path, unit_next_button_ele, log_callback, df_sheet)


def batch_add_note_ids(note_id, u_view_tab):
    u_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 批量添加 ').parent(2).click(by_js=True)
    footer_container = u_view_tab.ele('tag:div@@class=d-modal-footer')

    note_id_arr = note_id.strip().split('\n')
    u_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder=回车输入多个 ID，最多 100 条').run_js('this.focus();')

    for note in note_id_arr:
        u_view_tab.actions.input(note).input(Keys.ENTER)
        u_view_tab.wait(0.8)

    u_view_tab.ele('tag:a@@class$--size-text-paragraph btn-validate@@text()=搜索').click(by_js=True)
    footer_container.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=确认添加', timeout=2).parent(2).wait.enabled()
    footer_container.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=确认添加', timeout=2).parent(2).click(by_js=True)
    # u_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=取消', timeout=2).parent(2).click()
    u_view_tab.wait(1.5)


def choose_relative_pack(relative_pack, u_view_tab):
    u_view_tab.ele('tag:a@@class=d-text d-link --color-primary --size-text-paragraph relateTarget-btn@@text():关联定向包').click(by_js=True)  # 关联定向包
    u_view_tab.wait(1)
    if u_view_tab.ele(f'tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis@@text()={relative_pack}'):
        u_view_tab.ele( f'tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis@@text()={relative_pack}').parent(4).run_js(mock_click_js)
        u_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=确认关联').parent(2).click(by_js=True)  # 确认关联
        u_view_tab.wait(2)

def select_note_and_choose(note_id, u_view_tab):
    u_view_tab.ele('tag:span@@text()=添加笔记').click(by_js=True)
    if u_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder^请输入笔记ID', timeout=2):
        u_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder^请输入笔记ID').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', note_id)
        u_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder^请输入笔记ID').input(Keys.ENTER)
        u_view_tab.wait(1)
    # 点击笔记选择，点击笔记确定
    if note_choose_ele := u_view_tab.ele('tag:span@@class$--color-primary --size-text-small@@text()=选择', timeout=3):
        note_choose_ele.click(by_js=True)  ## 选择笔记
    if u_view_tab.ele('css:.footer-actions > .--color-bg-primary', timeout=1):
        u_view_tab.ele('css:.footer-actions > .--color-bg-primary').click(by_js=True)  # 笔记确定


def handle_operate_too_fast(unit_next_button_ele, unit_view_tab, unit_name, log_callback):
    max_retries = 10  # 最大重试次数
    retry_count = 0

    while retry_count < max_retries:
        # 先检查是否已经进入下一页
        # if unit_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder=请输入你的创意名称', timeout=2):
        #     break
        unit_next_button_ele.click(by_js=True)

        if unit_view_tab.ele('@text():操作频繁', timeout=1):
            log_message(log_callback, f"创建单元页面创建单元:{unit_name} - 触发操作频繁,正在重试({retry_count + 1}/{max_retries})", "red")
            logger.info(f"操作频繁，等待后重试 ({retry_count + 1}/{max_retries})")
            time.sleep(2 * (retry_count + 1))
            # try:
            #     unit_next_button_ele.click()
            # except NoRectError:
            #     log_message(log_callback, f"单元页面没找到下一步按钮:{unit_name} - 页面已跳转，停止重试", "green")
            #     break
            retry_count += 1
        else:
            break  # 没有"操作频繁"提示时退出循环

    if retry_count == max_retries:
        log_message(log_callback, f"单元名称:{unit_name} - 已达到最大重试次数，仍然操作频繁", "red")
        logger.error("已达到最大重试次数，仍然操作频繁")
    else:
        log_message(log_callback, f"单元名称: {unit_name}-在重试({retry_count + 1}/{max_retries})次后成功执行下一步", "green")
        logger.info("操作成功执行")


# if __name__ == '__main__':
#     file_path = r"../shared/唤端-创建计划-样例.xlsx"
#
#     browser = Chromium()  ## 临时测试、到时候删掉， 只保留调用create_unit()函数
#     unit_view_tab = browser.latest_tab  ## 临时测试、到时候删掉
#     unit_view_tab.get('https://ad.xiaohongshu.com/aurora/ad/create/unit/121968939/16/1?isStep=true&AFormGrayFlag=false&vSellerId=67403ef0c2f45c001519af4b')  ## 临时测试、到时候删掉
#
#     sheet1_data = get_complete_sheet1(file_path)
#     for index, row in sheet1_data.iterrows():
#         if index == 0:
#             create_unit(unit_view_tab, row, browser, file_path, df_sheet=sheet1_data)



